/* This file is part of REWise.
 *
 * REWise is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * REWise is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdlib.h>

#include "wiseoverlay.h"
#include "reader.h"
#include "print.h"


bool readWiseOverlayHeader(FILE * fp, WiseOverlayHeader * dest) {
  REWError status;
  int ch;

  // Init structure
  //dest->dllName     = NULL;  // We skip this
  dest->initTextLen = 0;
  dest->initTexts   = NULL;

  // Read dllNameLen
  ch = fgetc(fp);
  if (ch == EOF) {
    printError("Failed to read dllNameLen (EOF).\n");
    return false;
  }
  dest->dllNameLen = (unsigned char)ch;
  printDebug("dllNameLen: %d\n", dest->dllNameLen);

  // Skip dllName (string) and dllSize (int)
  if (dest->dllNameLen > 0) {
    if (fseek(fp, (long)(dest->dllNameLen + 4), SEEK_CUR) != 0) {
      printError("Failed to skip dllName.\n");
      return false;
    }
  }

  // Read crcFlags (int32)
  if ((status = readInt32(fp, &dest->crcFlags)) != REWERR_OK) {
    printError("Failed to read crcFlags. %d\n", status);
    return false;
  }

  // Read 86 unknown bytes
  if ((status = readBytesInto(fp, dest->unknown_86, 86)) != REWERR_OK) {
    printError("Failed to read 86 unknown bytes\n");
    return false;
  }

  // Read initTextLen
  ch = fgetc(fp);
  if (ch == EOF) {
    printError("Failed to read initTextLen (EOF).\n");
    return false;
  }
  dest->initTextLen = (unsigned char)ch;

  // Init texts
  printDebug("Read init texts, len: %d\n", dest->initTextLen);
  unsigned char * initTexts = malloc(sizeof(unsigned char) * dest->initTextLen);
  if (initTexts == NULL) {
    printError("Failed allocate memory for initTexts. Out of memory!\n");
    return false;
  }

  if ((status = readBytesInto(fp, initTexts, dest->initTextLen)) != REWERR_OK) {
    printError("Failed to read initTexts. %d\n", status);
    free(initTexts);
    return false;
  }
  dest->initTexts = initTexts;

  return true;
}


void freeWiseOverlayHeader(WiseOverlayHeader * data) {
  if (data->initTexts != NULL) {
    free(data->initTexts);
    data->initTexts = NULL;
  }
}
